// const modules = import.meta.glob('@/views/**/*.vue')
import { createRouter, createWebHistory } from "vue-router";
import { useRoutesStore } from "@/stores";
import type { Route, RouteChild } from "./type"; // 新增类型导入

const modules = import.meta.glob('@/views/**/*.vue');

// 初始化静态路由
const staticRoutes = [
  {
    path: "/",
    name: "login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/layout",
    name: "layout",
    component: () => import("@/layout/index.vue"),
    children: [],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes: staticRoutes,
});

// 添加动态路由方法
export function addDynamicRoutes() {
  const routesStore = useRoutesStore();
  const routes = routesStore.getRoutes as Route[];
  
  // 先移除所有已添加的动态路由
  router.getRoutes().forEach(route => {
    if (route.name && route.name.toString().includes('-')) {
      router.removeRoute(route.name);
    }
  });

  routes.forEach(route => {
    if (route.router_type === 0) { // 目录类型
      route.children?.forEach((child: RouteChild) => {
        // 修改：子路由使用绝对路径（直接取 child.path）
        const fullPath = child.path.replace(/^\/|\/$/g, '');  // 去除首尾多余斜杠
        const componentPath = `/src/views/${child.component}.vue`;
        
        if (!modules[componentPath]) {
          console.error(`Component not found: ${componentPath}`);
          return;
        }

        // 添加子路由到 layout 下（路径为绝对路径）
        router.addRoute('layout', {
          path: `/${fullPath}`,  // 确保以 / 开头
          name: `${route.name}-${child.name}`,
          component: modules[componentPath],
        });
      });
    } else { // 菜单类型（保持原有逻辑）
      const menuPath = route.path.startsWith('/') ? route.path : `/${route.path}`;
      router.addRoute('layout', {
        path: menuPath,
        name: route.name,
        component: modules[`/src/views/${route.component}.vue`],
      });
    }
  });
}

export default router;
